/*
 gifSlide or slutboxxx or whatever I end up calling this
	by Daniel Heffner
*/
var DEFAULT_DELAY_INTERVAL = 3275;
var DEFAULT_DELAY_STAGGER = 1;//no staggering
var DEFAULT_BOX_WIDTH = 240;
var DEFAULT_BOX_HEIGHT = 240;
var DEFAULT_URL = 'http://localhost:3000';

gifSlide = function(opts) {
    var _this = this;
    _this.opts = opts || {boxes:{width: DEFAULT_BOX_WIDTH,height: DEFAULT_BOX_HEIGHT}};
    _this.go = false;
    _this.paused = false;
    _this.boxCount = 0;
    _this.delayInterval = opts.delayInterval || DEFAULT_DELAY_INTERVAL;
    _this.delayStagger = opts.delayStagger || DEFAULT_DELAY_STAGGER;
    _this.allowUnconfirmed = opts.allowUnconfirmed || false;
    _this.base_url = opts.url || DEFAULT_URL;
    _this.disable_overlay_highlighting = false;
//todo
_this.selected_category = 'girls_gifs';

    this.makeSite = function() {
        this.accomodateWindow();
        this.setPageTitle(this.opts.title);
        this.logo(this.opts.categories[_this.selected_category].label);
        //create main sortable container
        var boxesContainer = $("<ul>", {id:"sortableBoxes", class: "sortableBoxes"}).sortable();
        //create modal dialog contents
        var dialogs = this._dialogContainers().hide();
        //create floating menu 
        var menu = this._floatingMenu(); //this._floatingElements();
        //append these bitches & apply upload display on hover
        var main = $("<div>",{id:"main",class:"main"}).append(menu,boxesContainer,dialogs)
            .mouseover(function(){
                $(".bodyHover").show();
            })
            .mouseout(function(){$(".bodyHover").hide();});
        $("body").append(main);
        //have to wait until after the appending of dom elements to body 
        //before we can add our jquery ui objects.
        this._jqueryUIobjs();	
        $(window).resize(function(){
            _this.accomodateWindow();
        });
    };
    this.newImage = function(image) {
        var ul = $("#sortableBoxes");
        if ( _this.boxCount >= _this.maxBoxes()) {
            ul.children("li:nth-child("+_this.maxBoxes()+")").animate({width:0,height:0},"slow").unbind().remove().delay(1200);
        }
        ul.prepend(_this._createBox(image));
        ul.children("li:nth-child(1)").animate({width:_this.opts.boxes.width,height:_this.opts.boxes.height},'slow');
        _this.boxCount = ul.children("li").length;
        _this.delayInterval = _this.delayInterval * _this.delayStagger;
    }
    //start the slide
    this.startIterator = function() {
        if (_this.go) { return; } //iterator is already running	
        _this.go = true;
        _this.current_interval = setInterval(function() {
            _this.doOne();
        },_this.delayInterval)
    }
    this.doOne = function() {
        $.ajax({
            url : _this.base_url + '/image/random_image',
            data: { category: _this.selected_category, allow_unverified: (_this.allowUnconfirmed ? 1 : 0) },
            jsonp: 'cb', dataType: 'jsonp',
            success: function(data,textStatus,jqXHR){
                if (data.rest.webservice_error) { console.log(data) }
                else { _this.newImage(data.rest.image); }
            }
        });
    }
    //stop the slide
    this.stopIterator = function() {
        window.clearInterval(_this.current_interval);
        this.go = false;
        _this.delayInterval = _this.opts.delayInterval || DEFAULT_DELAY_INTERVAL;
    }
    this.reboot = function() { _this.stopIterator(); _this.startIterator(); }
    //ldo
    this.setPageTitle = function(title) {
        this.title = title;
        document.title = this.title;	
    }
    this.logo = function(category) {
        $('<div>',{id:'logo_wrap', class: 'logo'}).append(
            $('<div>',{id:'logoSquare',class:'logoSquare'}),
            $('<div>',{id:'logo'}).text(_this.title),
            $('<div>',{id:'sublogo',class:'sublogo'}).text(category)
        ).appendTo("body");
    }
    this.changeCategory = function(id,label) {
        //_this.selected_category = id;
        $("#sublogo").text(label);
    }
    //check window height/width. pass to setGridDimensions
    this.accomodateWindow = function() {
        var $win = $(window);
        var width = $win.width();
        var height = $win.height();
        _this.setGridDimensions(width,height);		
        _this.removeExtraneousBoxes();
    }
    //remove any boxes that are beyond our maxBoxes
    this.removeExtraneousBoxes = function() {
        while ($("#sortableBoxes > li").length > _this.maxBoxes()) {
            $("#sortableBoxes").children("li:nth-child("+_this.maxBoxes()+")").unbind().remove();
        }
    }

    //compare box area vs window area and determine how many rows and columns we can fit
    this.setGridDimensions = function(w,h) {
        _this.cols = Math.floor(w / _this.opts.boxes.width);
        _this.rows = Math.floor(h / _this.opts.boxes.height);
    }
    //max boxes before remove
    this.maxBoxes = function() {
        return _this.rows * _this.cols;
    }
    this._createBox = function(image) {
        var id = image.id;

        var overlayClasses = ['boxOverlay'];
        if (_this.allowUnconfirmed && !image.verified) {
            if (!_this.disable_overlay_highlighting) overlayClasses.push('unverifiedOverlay');
        } else if (image.verified_by_user) {
            if (!_this.disable_overlay_highlighting) overlayClasses.push('verifiedOverlay');
        }

        var li 	= $("<li>").width(0).height(0);
        var div = $("<div>",{id: 'boxMain-' + id, class: "boxMain"});
        var file_type = 'image/gif'; 
        var img_src = 'data:' + file_type + ';base64,' + image.base64;
        var img = $("<img>",{id:'boxImg-' + id, class: 'boxImg', src: img_src, height: _this.opts.boxes.height, width: _this.opts.boxes.width, border:0});
        var overlay = $("<div>",{id: "boxOverlay-" + id, class: overlayClasses.join(' ')});

        div.append(img,overlay).hover(function(){
           var $child = $(this).find(".boxOverlay");
           var $button = $(this).find(".reportButton, .verifyButton, .verified-check-icon");
           if ($child.is(":visible")) { $child.hide(); $button.hide();}
           else {$child.show(); $button.show();}
        });

        if (image.verified) {
            var checkMark = $("<div>",{class:"verified-check-icon"}).append($("<span>",{class: 'ui-icon ui-icon-circle-check'}));
            div.append(checkMark);
        } else {
            var rptBtn = $("<button>",{id:"boxReportButton-" + id, class:'reportButton standardButton'}).text('Report Image').click(function(e){
                var btn_id = $(this).attr('id');
                var image_id = btn_id.match(/^boxReportButton-(.*?)$/)[1];
                _this.selected_image_id = image_id;
                $("#reportDialog").dialog("open");
                _this.stopIterator();
            });
            var verifyButton = $("<button>",{id: "boxVerifyButton-" + id,class:'verifyButton standardButton'});
            verifyButton.text('Verify?').click(function(){
                var btn_id = $(this).attr('id');
                var image_id = btn_id.match(/^boxVerifyButton-(.*?)$/)[1];
                $.ajax({
                    url: _this.base_url + "/image/verify",
                    type: 'POST',
                    data: {
                        image_id: image_id, 
                    },
                    jsonp: 'cb', dataType: 'jsonp',
                    success: function(data,textStatus,jqXHR){
                        if (data.rest.webservice_error) { _this.handleError(data.rest.webservice_error)}
                        else { 
                            $("#boxVerifyButton-" + image_id).text("You Verified!").unbind(); 
                            if (!_this.disable_overlay_highlighting) {
                                $("#boxOverlay-" + image_id).removeClass('unverifiedOverlay').addClass("verifiedOverlay");
                            } 
                            $("#boxReportButton-" + image_id).unbind().remove();
                            var checkMark = $("<div>",{class:"verified-check-icon"}).append($("<span>",{class: 'ui-icon ui-icon-circle-check'}));
                            $("div#boxMain-" + image_id).append(checkMark);
                        }
                    },
                    error: function(e,t,j) { console.log(e); } 
                });
            });

            div.append(verifyButton,rptBtn);
        }
        li.append(div);
        return li;
    }
    this._floatingMenu = function() {
        var divMenu = $("<div>",{id: "floatingMenu", class:"floatingMenu bodyHover"});
        //snap bars
        var divSnap = $("<div>",{id: "menuSnapTop", class:"menuSnap"});
        var snapSpan = $("<span>",{id: "snapSpanTop", class: "snapSpan ui-icon ui-icon-triangle-1-s"}).click(function(){
            $("#floatingMenuInner,#menuExtSnap").toggle();
            var $this = $(this);
            $this.toggleClass('ui-icon-triangle-1-s');
            $this.toggleClass('ui-icon-triangle-1-n');
        }).appendTo(divSnap);
        var divExtSnap = $("<div>",{id: "menuExtSnap", class:"menuSnap"});
        var snapExtSpan = $("<span>",{id: "snapExtSpan", class: "snapSpan ui-icon ui-icon-triangle-1-n"}).click(function(){
            $("#divExtMenu").toggle('slow');
            var $this = $(this);
            $this.toggleClass('ui-icon-triangle-1-n');
            $this.toggleClass('ui-icon-triangle-1-s');
            $this.parent().parent().toggleClass('floatingMenuBottom');
        }).appendTo(divExtSnap);
        //menus
        var divMenuInner = $("<div>",{id: "floatingMenuInner", class:"floatingMenuInner"});
        var pauseButton = $("<button>",{id:"pauseButton",class:"standardButton menuButton iconOnly"})
            .append($("<span>",{id: "pauseButtonSpan", class:"ui-icon ui-icon-pause"}))
            .click(function(){ _this.paused = true; _this.stopIterator(); });
        var playButton = $("<button>",{id:"playButton",class:"standardButton menuButton iconOnly"})
            .append($("<span>",{id: "playButtonSpan", class:"ui-icon ui-icon-play"}))
            .click(function(){ _this.paused = false; _this.startIterator();});
        var unverifiedToggle = $("<button>",{id:"unverifiedToggle",class: "standardButton menuButton unverifiedToggle"}).text("Allow Unverified Images?")
            .click(function(){
                var $this = $(this);
                if (_this.allowUnconfirmed) {
                    _this.allowUnconfirmed = false;
                    $this.text("Allow Unverified Images?");
                    _this.removeAllUnconfirmed();
                    _this.reboot();
                } else {
                    _this.allowUnconfirmed = true;
                    $this.text("Go back to Pre-Verified Only");
                    _this.reboot();
                }   
            });
        var categoryWrap = $("<span>",{class:"categoryWrap"});
        var categoryButton = $("<button>",{id:"categorySet",class:"inactiveButton buttonPairLeft"}).text("Set Category");
        var categorySelector = $("<button>",{id:"categorySelector",class:"standardButton menuButton buttonPairRight iconOnly splitButton"}).append(
            $("<span>",{id:"categorySelectorIcon",class:"ui-icon ui-icon-triangle-1-s dropDownIcon"})
        ).click(function(){
            $("#categoryList").toggle();
        })
        var categoryList = $("<ul>",{id: "categoryList",class:"categoryList"});
        console.log(_this.opts);
        $.each(_this.opts.categories,function(n,m) {
            var placeHolder = $("<span>",{class:"iconPlaceholder"});
            if (n == _this.selected_category) {
                placeHolder.addClass('currentlySelectedItem').addClass('ui-icon').addClass('ui-icon-check');
            }
            categoryList.append(
                $("<li>",{id:n}).append(
                    placeHolder,
                    $("<span>",{class:"listText"}).text(m.label)
                ).click(function(){
                    $('.currentlySelectedItem').removeClass('currentlySelectedItem').removeClass('ui-icon').removeClass('ui-icon-check');
                    $this = $(this);
                    $this.addClass('currentlySelectedItem');
                    console.log($this);
                    $this.children('.iconPlaceholder').addClass('ui-icon').addClass('ui-icon-check').addClass('currentlySelectedItem');
                    //_this.selected_category = $this.attr('id');
                    _this.changeCategory($this.attr('id'),$this.text());
                })
            );
        });
        categoryWrap.append(categoryButton,categorySelector,categoryList.hide());

        var uploadButton = $("<button>",{id:"uploadButton",class:"standardButton menuButton"}).text("Upload!")
            .click(function(){ $("#uploadDialog").dialog("open"); _this.stopIterator();});
        divMenuInner.append(pauseButton,playButton,unverifiedToggle,categoryWrap,uploadButton);
        

        var divExtMenu = $("<div>",{id:"divExtMenu",class:"floatingMenuInner extendedMenu"}).hide();
        if (Array.isArray(_this.opts.ext_menu_opts)) {
            var menu_opts = _this.opts.ext_menu_opts;
            menu_opts.each(function(n) {    
                var label = $("<label>",{id:'label-'+n.id, for: n.id,class:"extMenuLabel"}).text(n.label);
                if(Array.isArray(n.values)) {
                    var select = $("<select>",{id:n.id, name:n.id});
                    var opts = [];
                    n.values.each(function(m){
                        opts.push($("<option>").val(m).text(m));
                    });
                    select.append(opts);
                    divExtMenu.append(label,select);
                } else {
                    divExtMenu.append(
                        label, $("<input>",{id:n.id, type: n.type, name:n.id}).click(function(){
                            $this = $(this);
                            var isChecked = $this.attr('checked')?true:false;
                            _this[$this.attr('id')] = isChecked;
                        })
                    )
                }
            });
        }
    
        divMenu.append(divSnap,divMenuInner,divExtSnap,divExtMenu);
        return divMenu;
    }

    this.removeAllUnconfirmed = function() {
        $(".unverifiedOverlay").parent("div").parent("li").hide("explode", 2850).unbind().remove();
    }
    this._dialogContainers = function() {
        var containerDiv = $("<div>",{id: "modalContainer"});
        var uploadDiv = $("<div>",{id: "uploadDialog", class:"modalDialog"});
        var reportDiv = $("<div>",{id: "reportDialog", class:"reportDialog"}).append(
            $("<div>",{id: 'reportMainText', class: 'reportMainText'}).text(_this.opts.categories[_this.selected_category].report_text)
        );

        var uploadForm = $("<form>",{id:"uploadForm", enctype: "multipart/form-data"}); 
//        var filesDiv = $("<div>",{id: 'files', class: 'files'});
//        var fileUpload = $("<input>",{type: 'file', id:'filedata', multiple: true, name: 'files[]'})//.hide()
//        uploadForm.append(filesDiv,fileUpload);
        uploadForm.appendTo(uploadDiv);

    
        var reportForm = $("<form>",{id: "reportForm"});
        var buttonSet = $("<div>",{id:"radioButtonSet"}).appendTo(reportForm);
        _this.opts.categories[_this.selected_category].reasons.each(function(n){
            buttonSet.append(
                $("<input>",{id: 'reportForm-choice-' + n.id, type:'radio', name:'reportRadio'}),
                $("<label>",{id: 'reportForm-label-' + n.id, 'for': 'reportForm-choice-'+n.id}).text(n.label)
            );
        });
        reportForm.appendTo(reportDiv);	
	
        return containerDiv.append(uploadDiv,reportDiv);
    }
    this._jqueryUIobjs= function() {
        $("#uploadDialog").dialog({
            autoOpen: false, resizable: false, modal: true,
            height: 400, width: 400, title: "Upload Gif",
            buttons: {
//                "Select Files": function(e){ 
//                   // console.log(e);
//                   //$("#fileList").click();
//                   //$("#uploadForm").fileupload('add',{files: filesList});
//                },
//                Upload: function(){ alert("todo");},
                Cancel: function(){
                    $(this).dialog("close");
                    if(!_this.paused) {_this.startIterator();}
                },
            }
        });

//        var uploadForm = $("<form>",{id:"uploadForm", enctype: "multipart/form-data"});
//        var fileUpload = $("<input>",{type: 'file', id:'filedata', multiple: true, name: 'files[]'})//.hide()
//        fileUpload.appendTo(uploadForm);
//        uploadForm.appendTo(uploadDiv);
//        $("#uploadDialog").next().find('button.ui-button').first().children('span').after(fileUpload).wrap(uploadForm);


        $("#reportDialog").dialog({
            autoOpen: false, resizable: false, modal: true,
            minHeight: 210, minWidth: 360, title: "Report Image",
            buttons: {
                "Send Report": function(){ 
                    var reason = $('input[name=reportRadio]:checked').attr('id').match(/^reportForm-choice-(.*?)$/)[1];
                    console.log(reason,_this.selected_image_id,_this.selected_category);
                    $.ajax({
                        url: _this.base_url + '/image/report',
                        jsonp: 'cb', dataType: 'jsonp',
                        data: { category: _this.selected_category, image_id: _this.selected_image_id, report_reason: reason },
                        success: function(data){
                            if (data.rest.webservice_errror) { _this.handleError(data.rest.webservice_errror) }
                            else {
                                console.log(data);
                                $("div#boxMain-" + _this.selected_image_id).parent("li").hide("explode", 2850).unbind().remove();
                            }
                        }
                    });
                    $(this).dialog("close");
                    if(!_this.paused) {_this.startIterator();}
                },
                Cancel: function() {
                    $(this).dialog("close");
                    if(!_this.paused) {_this.startIterator();}
                }
            }
        });	

        // Initialize the jQuery File Upload widget:
        $('#filedata').fileupload({
            url: _this.base_url + '/image/upload',
            sequentialUploads: true,//TODO set false, need to adjust controller first tho
            dataType: 'json',
            type: 'POST',
            paramName: 'filedata',
            limitMultiFileUploads: 3,
            formData: function() {
//TODO comes from another form obj so they can select any category in one upload modal
                return {
                    category: _this.selected_category
                }
            },
            maxFileSize: 5000000,
            acceptFileTypes: /(\.|\/)(gif)$/i, 
            previewSourceFileTypes: /(\.|\/)(gif)$/i,
            filesContainer: "#uploadDialog"
        });

    	// Enable iframe cross-domain access via redirect option:
//	    $('#fileupload').fileupload(
//    	    'option',
//        	'redirect',
//	        window.location.href.replace(
//    	        /\/[^\/]*$/,
//        	    '/cors/result.html?%s'
//	        )
//    	);
		
//        $('#uploadForm').fileupload('option', {
//            url: _this.base_url + '/image/upload',
//            maxFileSize: 5000000,
//            acceptFileTypes: /(\.|\/)(gif)$/i,
//            process: [
//                {
 //                   action: 'load',
   //                 fileTypes: /^image\/(gif)$/,
    //                maxFileSize: 5000000 // 20MB
    //            },
    //            {
                //    action: 'resize',
              //      maxWidth: 1440,
            //        maxHeight: 900
        //        },
          //      {
      //              action: 'save'
  //              }
    //        ]
//        });
        $("#radioButtonSet").buttonset();
        //lightbox... pauses/unpauses
//        $("a.lb-close, #lightboxOverlay").click(function(){
  //          if (!_this.paused) { _this.startIterator(); }
  //      });
    }

    this.handleError = function(msg) {
        if (!msg) return 0;
        console.log(msg);
    }

    _this.makeSite();
    if(_this.opts.autoStart) _this.doOne && _this.startIterator();
    return _this;
}


$(document).ready(function(){
    var config = {};
    var gifSlider = {};
    $.ajax({
        url:'http://localhost:3000/image/site_options',
        jsonp: 'cb', dataType: 'jsonp',
        success: function(data){
            config = data.rest;
            if(config.size == 0) { return; }
            gifSlider = new gifSlide(config);
        },
    });
});
